<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>push</title>
</head>
<body>
name: <input type="text" id="streamName" value="one"> <br/>
<button onclick="pushStream()">PUSH</button>
<br/>

<video id="video1" width="640" height="480" autoplay muted></video>
<br/>

<div id="logs"></div>
<br/>

</body>
</html>

<script>

    let pc = new RTCPeerConnection()

    function log(msg) {
        document.getElementById('logs').innerHTML += msg + '<br>'
        console.log(msg)
    }

    pc.oniceconnectionstatechange = function () {
        log("iceConnectionState: " + pc.iceConnectionState)
    }

    pc.onicecandidate = function (event) {
        if (event.candidate != null) {
            log("candidate: " + JSON.stringify(event.candidate))
        }
    }


    function pushStream() {
        let streamName = document.getElementById("streamName").value;
        let protocol = "ws://"
        if (window.location.protocol === "https:") {
            protocol = "wss://"
        }
        let wsURL = protocol + window.location.hostname + ":" + window.location.port + "/ws/push/" + streamName;

        let ws = new WebSocket(wsURL)
        ws.onopen = (e) => {
            console.log(e)

            navigator.mediaDevices.getUserMedia({video: true, audio: false})
                .then(function (stream) {
                    document.getElementById('video1').srcObject = stream

                    stream.getTracks().forEach(track => pc.addTrack(track, stream))

                    pc.createOffer({})
                        .then(offer => {
                            pc.setLocalDescription(offer)

                            ws.send(JSON.stringify({
                                method: "offer",
                                offer: {
                                    offer: offer
                                },
                            }))
                        })
                        .catch(function (e) {
                            log(e)
                        })

                })
                .catch(function (e) {
                    log(e)
                })
        }
        ws.onclose = (e) => {
            console.log(e)
        }
        ws.onerror = (e) => {
            console.log(e)
        }
        ws.onmessage = (e) => {
            log(e.data)

            let object = JSON.parse(e.data)
            if (object.answer.code === 0) {
                pc.setRemoteDescription(object.answer.answer)
            }
        }
    }

</script>